package com.example.librarymanagementsystembackend.bookmanagement.service;

import com.example.librarymanagementsystembackend.bookmanagement.entity.BookCategory;
import com.example.librarymanagementsystembackend.bookmanagement.entity.BookCategoryDatabaseEntity;
import com.example.librarymanagementsystembackend.bookmanagement.entity.BookInformation;
import com.example.librarymanagementsystembackend.bookmanagement.mapper.BookMapper;
import com.example.librarymanagementsystembackend.utils.InvalidRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BookService {

    @Autowired
    private BookMapper bookMapper;
    private final int NOT_CLASSIIFIED = 11;

    public List<BookCategory> getBookCategories() {
        List<BookCategoryDatabaseEntity> bookCategoryDatabaseEntities = bookMapper.getBookCategoryDatabaseEntities();

        // 第一遍：构造BookCategory与其id的映射
        Map<Integer, BookCategory> categoryMap = new HashMap<>();
        for (BookCategoryDatabaseEntity categoryDatabaseEntity : bookCategoryDatabaseEntities) {
            BookCategory category = new BookCategory();
            category.setId(categoryDatabaseEntity.getId());
            category.setName(categoryDatabaseEntity.getName());
            categoryMap.put(categoryDatabaseEntity.getId(), category);
        }

        // 第二遍：构建图书类别父子关系
        List<BookCategory> rootCategories = new ArrayList<>();
        for (BookCategoryDatabaseEntity categoryDatabaseEntity : bookCategoryDatabaseEntities) {
            BookCategory category = categoryMap.get(categoryDatabaseEntity.getId());
            int parentId = categoryDatabaseEntity.getParentId();
            if (parentId == 0) { // 是根类别，添加到根类别数组
                rootCategories.add(category);
            } else { // 是子类别，添加到父类别的children数组
                BookCategory parent = categoryMap.get(parentId);
                if (parent != null) {
                    parent.getChildren().add(category);
                }
            }
        }

        // 第三遍：加入图书
        List<BookInformation> books = bookMapper.getAllBooks();
        for (BookInformation book : books) {
            int categoryId = book.getCategoryId();
            if (categoryMap.containsKey(categoryId)) {
                BookCategory bookCategory = categoryMap.get(categoryId);
                bookCategory.getBooks().add(book);
            }
        }

        return rootCategories;
    }

    public void addBook(BookInformation bookInformation) {
        String isbn = bookInformation.getIsbn();
        if (isbn == null) {
            throw new InvalidRequestException("新增图书缺少ISBN");
        }
        if (bookMapper.hasIsbn(isbn)) {
            throw new InvalidRequestException("本馆图书已存在该ISBN");
        }
        // 图书类别为默认值null或0（未指定图书类别）
        Integer categoryId = bookInformation.getCategoryId();
        if (categoryId == null || categoryId == 0) {
            bookInformation.setCategoryId(this.NOT_CLASSIIFIED);
        }
        if (bookMapper.addBook(bookInformation) == 0) {
            throw new InvalidRequestException("数据库接口异常");
        }
    }

    public BookInformation getBookById(int id) {
        if (!bookMapper.hasId(id)) {
            throw new InvalidRequestException(404, "该ID对应的书不存在");
        }
        BookInformation book = bookMapper.getBookById(id);
        if (book == null) {
            throw new InvalidRequestException("数据库接口异常");
        }
        return book;
    }

    public void deleteBookById(int id) {
        if (!bookMapper.hasId(id))
            throw new InvalidRequestException(404, "该ID对应的书不存在");
        if (bookMapper.deleteBookById(id) == 0) {
            throw new InvalidRequestException("数据库接口异常");
        }
    }

    public void updateBook(BookInformation bookInformation) {
        if (!bookMapper.hasId(bookInformation.getId()))
            throw new InvalidRequestException(404, "该ID对应的书不存在");

        BookInformation bookWithSameIsbn = bookMapper.getBookByIsbn(bookInformation.getIsbn());
        if (bookWithSameIsbn != null && bookWithSameIsbn.getId() != bookInformation.getId()) {
            throw new InvalidRequestException("本馆图书已存在该ISBN");
        }

        if (bookMapper.updateBook(bookInformation) == 0) {
            throw new InvalidRequestException("数据库接口异常");
        }
    }

    public List<BookInformation> queryBooks(int pageSize, int pageIndex) {
        try {
            return bookMapper.queryBooks((pageIndex - 1) * pageSize, pageSize);
        } catch (Exception e) {
            throw new InvalidRequestException(e.getMessage());
        }
    }
}
